package bupt.party.online.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;



import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import bupt.party.online.dto.BranchStudyRecordDTO;
import bupt.party.online.dto.PartyStudyRecordDTO;
import bupt.party.online.dto.PersonStudyRecordDTO;
import bupt.party.online.model.Admin;
import bupt.party.online.model.Branch;
import bupt.party.online.model.Student;
import bupt.party.online.service.IAdminService;
import bupt.party.online.service.IBranchService;
import bupt.party.online.service.ILearnRecordService;
import bupt.party.online.service.IStudentService;
import bupt.party.online.util.BuptPartyConfig;
import bupt.party.online.util.SessionConstants;
import bupt.party.online.video.Video;
import bupt.party.online.video.VideoMgr;
import bupt.party.online.vo.Nationality;
import bupt.party.online.vo.Year;

public class AdminAction extends Pagination implements ServletRequestAware, ServletResponseAware{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	private HttpServletRequest request;
    private HttpServletResponse response; 
    
	private IStudentService studentService;
	private IAdminService adminService;
	private IBranchService branchService;
	private ILearnRecordService learnRecordService;
	
	private Nationality nationality;
	private Year year;
	
	private List<Student>  currentStudentList;
	private List<Admin>    currentAdminList;
	
	private List<PersonStudyRecordDTO> personStudyRecordList = new ArrayList<PersonStudyRecordDTO>();
	private List<BranchStudyRecordDTO> branchStudyRecordList = new ArrayList<BranchStudyRecordDTO>();
	private List<PartyStudyRecordDTO> partyStudyRecordList = new ArrayList<PartyStudyRecordDTO>();
	private String paginationCode;
	
	
	private Integer parentId;   //分党委id
	private String xmlString;   //生成支部结构的数据信息
	private List<Branch> firstPaList = new ArrayList<Branch>();//党委列表
	private List<Branch> secondPaList = new ArrayList<Branch>();;//支部列表
	private Integer firstPa = -1;
	private Integer secondPa = -1;
	
	//保存查询条件到下一个界面
	private  Integer firstPaHidden = -1;
	private  Integer secondPaHidden = -1;
	
	
	private String adminName;
	private String adminNO;
	private String sfzNO;
	private String adminNationality;
	private String adminGender;
	private String telephone;
	private String email;
	private String adminPassword;
	
	
	
	private String studentName="";
	private String studentNO="";
	private String studentSfzNO;
	private String studentNationality;
	private String studentGender;
	private String studentBranchId;
	private String studentTelephone;
	private String studentEmail; 
	private String studentPassword;
	
	
	private String oldPassword;

	private String newPassword;

	private String newPassword2;
	
	private String result = "";
	
	
	private String userId;//重置账号id
	private String userNewPassword;//重置新密码
	private String userNewPassword2;//
	private String userstatus = "0";// 0为游客 ；1为学生； 2为管理员
	
	
	//查询条件
	private Integer highLevelQuery=-1;
	private String queryContent="";
	
	//for get branch name
	private Map<Integer, String> branchIdToNameMap;
	
	//for get particpateRate
	private Map<Integer,String> branchIdToRateMap;
	
	
	//branchName
	public String branchName;
	
	
	//导出excel文件
	private String fileFileName;
    private String downloads;
    private String downloadFilename;
	
	
	//统计学习情况
	private String currentYear = BuptPartyConfig.subString(new Timestamp(System.currentTimeMillis()).toString(), 4);
	
	
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	
	
	public IStudentService getStudentService() {
		return studentService;
	}


	public void setStudentService(IStudentService studentService) {
		this.studentService = studentService;
	}




	public IAdminService getAdminService() {
		return adminService;
	}


	public void setAdminService(IAdminService adminService) {
		this.adminService = adminService;
	}


	
	public IBranchService getBranchService() {
		return branchService;
	}

	public void setBranchService(IBranchService branchService) {
		this.branchService = branchService;
	}
	
	
	public ILearnRecordService getLearnRecordService() {
		return learnRecordService;
	}

	public void setLearnRecordService(ILearnRecordService learnRecordService) {
		this.learnRecordService = learnRecordService;
	}

	public Nationality getNationality() {
		return nationality;
	}

	public void setNationality(Nationality nationality) {
		this.nationality = nationality;
	}
	
	
	public Year getYear() {
		return year;
	}

	public void setYear(Year year) {
		this.year = year;
	}

	public String getAdminName() {
		return adminName;
	}

	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}


	public String getAdminNO() {
		return adminNO;
	}

	public void setAdminNO(String adminNO) {
		this.adminNO = adminNO;
	}

	public String getSfzNO() {
		return sfzNO;
	}

	public void setSfzNO(String sfzNO) {
		this.sfzNO = sfzNO;
	}

	

	public String getAdminNationality() {
		return adminNationality;
	}

	public void setAdminNationality(String adminNationality) {
		this.adminNationality = adminNationality;
	}

	public String getAdminGender() {
		return adminGender;
	}

	public void setAdminGender(String adminGender) {
		this.adminGender = adminGender;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}


	public String getAdminPassword() {
		return adminPassword;
	}

	public void setAdminPassword(String adminPassword) {
		this.adminPassword = adminPassword;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public String getStudentNO() {
		return studentNO;
	}

	public void setStudentNO(String studentNO) {
		this.studentNO = studentNO;
	}

	public String getStudentSfzNO() {
		return studentSfzNO;
	}

	public void setStudentSfzNO(String studentSfzNO) {
		this.studentSfzNO = studentSfzNO;
	}

	public String getStudentNationality() {
		return studentNationality;
	}

	public void setStudentNationality(String studentNationality) {
		this.studentNationality = studentNationality;
	}

	public String getStudentGender() {
		return studentGender;
	}

	public void setStudentGender(String studentGender) {
		this.studentGender = studentGender;
	}

	public String getStudentBranchId() {
		return studentBranchId;
	}

	public void setStudentBranchId(String studentBranchId) {
		this.studentBranchId = studentBranchId;
	}


	public String getStudentTelephone() {
		return studentTelephone;
	}

	public void setStudentTelephone(String studentTelephone) {
		this.studentTelephone = studentTelephone;
	}

	public String getStudentEmail() {
		return studentEmail;
	}

	public void setStudentEmail(String studentEmail) {
		this.studentEmail = studentEmail;
	}


	

	public Integer getFirstPa() {
		return firstPa;
	}

	public void setFirstPa(Integer firstPa) {
		this.firstPa = firstPa;
	}

	public Integer getSecondPa() {
		return secondPa;
	}

	public void setSecondPa(Integer secondPa) {
		this.secondPa = secondPa;
	}
	
	public Integer getFirstPaHidden() {
		return firstPaHidden;
	}

	public void setFirstPaHidden(Integer firstPaHidden) {
		this.firstPaHidden = firstPaHidden;
	}

	public Integer getSecondPaHidden() {
		return secondPaHidden;
	}

	public void setSecondPaHidden(Integer secondPaHidden) {
		this.secondPaHidden = secondPaHidden;
	}

	public String getStudentPassword() {
		return studentPassword;
	}

	public void setStudentPassword(String studentPassword) {
		this.studentPassword = studentPassword;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getNewPassword2() {
		return newPassword2;
	}

	public void setNewPassword2(String newPassword2) {
		this.newPassword2 = newPassword2;
	}


	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserstatus() {
		return userstatus;
	}

	public void setUserstatus(String userstatus) {
		this.userstatus = userstatus;
	}

	

	public Integer getHighLevelQuery() {
		return highLevelQuery;
	}

	public void setHighLevelQuery(Integer highLevelQuery) {
		this.highLevelQuery = highLevelQuery;
	}

	public String getQueryContent() {
		return queryContent;
	}

	public void setQueryContent(String queryContent) {
		this.queryContent = queryContent;
	}
	

	public String getBranchName() {
		return branchName;
	}

	public void setBranchName(String branchName) {
		this.branchName = branchName;
	}
	
	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getDownloads() {
		return downloads;
	}

	public void setDownloads(String downloads) {
		this.downloads = downloads;
	}

	public String getDownloadFilename() {
		return downloadFilename;
	}

	public void setDownloadFilename(String downloadFilename) {
		this.downloadFilename = downloadFilename;
	}

	public String getCurrentYear() {
		return currentYear;
	}

	public void setCurrentYear(String currentYear) {

		this.currentYear = currentYear;
		
	}

	public Map<Integer, String> getBranchIdToNameMap() {
		return branchIdToNameMap;
	}

	public void setBranchIdToNameMap(Map<Integer, String> branchIdToNameMap) {
		this.branchIdToNameMap = branchIdToNameMap;
	}
	
	public Map<Integer, String> getBranchIdToRateMap() {
		return branchIdToRateMap;
	}

	public void setBranchIdToRateMap(Map<Integer, String> branchIdToRateMap) {
		this.branchIdToRateMap = branchIdToRateMap;
	}

	public String getUserNewPassword() {
		return userNewPassword;
	}

	public void setUserNewPassword(String userNewPassword) {
		this.userNewPassword = userNewPassword;
	}

	public String getUserNewPassword2() {
		return userNewPassword2;
	}

	public void setUserNewPassword2(String userNewPassword2) {
		this.userNewPassword2 = userNewPassword2;
	}

	public List<PersonStudyRecordDTO> getPersonStudyRecordList() {
		return personStudyRecordList;
	}

	public void setPersonStudyRecordList(
			List<PersonStudyRecordDTO> personStudyRecordList) {
		this.personStudyRecordList = personStudyRecordList;
	}

	public List<BranchStudyRecordDTO> getBranchStudyRecordList() {
		return branchStudyRecordList;
	}

	public void setBranchStudyRecordList(
			List<BranchStudyRecordDTO> branchStudyRecordList) {
		this.branchStudyRecordList = branchStudyRecordList;
	}

	public List<PartyStudyRecordDTO> getPartyStudyRecordList() {
		return partyStudyRecordList;
	}

	public void setPartyStudyRecordList(
			List<PartyStudyRecordDTO> partyStudyRecordList) {
		this.partyStudyRecordList = partyStudyRecordList;
	}

	

	public List<Student> getCurrentStudentList() {
		return currentStudentList;
	}

	public void setCurrentStudentList(List<Student> currentStudentList) {
		this.currentStudentList = currentStudentList;
	}
	
	public List<Admin> getCurrentAdminList() {
		return currentAdminList;
	}

	public void setCurrentAdminList(List<Admin> currentAdminList) {
		this.currentAdminList = currentAdminList;
	}

	public Integer getParentId() {
		return parentId;
	}

	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}

	public String getXmlString() {
		return xmlString;
	}

	public void setXmlString(String xmlString) {
		this.xmlString = xmlString;
	}

	public List<Branch> getFirstPaList() {
		return firstPaList;
	}

	public void setFirstPaList(List<Branch> firstPaList) {
		this.firstPaList = firstPaList;
	}

	public List<Branch> getSecondPaList() {
		return secondPaList;
	}

	public void setSecondPaList(List<Branch> secondPaList) {
		this.secondPaList = secondPaList;
	}

	public String getPaginationCode() {
		return paginationCode;
	}

	public void setPaginationCode(String paginationCode) {
		this.paginationCode = paginationCode;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	
	
	
	/**
	 * 个人中心
	 * @return
	 */
	public String  adminPersonCenter(){
		
		return "redirectAdminInfo";
	}
	
	
	
	
	
	/*
	 * 用户管理
	 */
	public String  manageUser(){
		
		return "redirectMemberList";
	}
	
	
	
	/**
	 * 增加学生UI
	 * @return
	 */
	public String  addStudent(){
		
		
		//传给前台的是支部列表。。。。。wangdong
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		
		return "addStudent";
	}
	
	
	
	/**
	 * 新增学生用户保存
	 * @return
	 */
	public String  save_addStudent(){
		
		Student check_student  = studentService.findStudentByStudentNO(studentNO);
		if(check_student!=null){
			result = "添加用户失败，该学号已被注册！";
			
			return "save_addStudent";
		}
		
		Student student = new Student();
		
		student.setStudentNo(studentNO);
		student.setStudentEmail(studentEmail);
		student.setStudentGender(studentGender);
		student.setStudentIdentity(studentSfzNO);
		student.setStudentName(studentName);
		student.setStudentNationality(studentNationality);
		student.setStudentTelephone(studentTelephone);
		
		student.setStudentBranchId(secondPa);//第三级别‘支部’
		
		//学生的初始密码怎么弄,管理员设置初始密码。
		student.setstudentPassword(studentPassword);
		//不为空的3个属性
		student.setIsDelete(0);
		student.setStudentLearnTime(0.0);
		student.setAdminLevel(SessionConstants.STU_LEVEL);
		
		studentService.saveOrUpdateStudent(student);
		
		result = "添加用户成功！";
		return "save_addStudent";
	}
	
	
	
	
	/**
	 * 增加管理员UI
	 * @return
	 */
	public String  addAdministrator(){
		if(this.checkForAuth(SessionConstants.ADMIN_FIRST_LEVEL)) return "noPermission";
		//传给前台的是支部列表。。。。。wangdong
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		return "addAdministrator";
	}
	
	/**
	 * 新增管理员用户保存
	 * @return
	 */
	public String  save_addAdministrator(){
		if(this.checkForAuth(SessionConstants.ADMIN_FIRST_LEVEL)) return "noPermission";
		Admin check_admin  = adminService.findAdminByAmdinNO(adminNO);
		if(check_admin!=null){
			result = "添加用户失败，该工号已被注册！";
			
			return "save_addAdministrator";
		}
		
		Admin admin = new Admin();
		
		admin.setAdminEmail(email);
		admin.setAdminGender(adminGender);
		admin.setAdminIdentity(sfzNO);
		//判断管理员的级别
		if(secondPa!=-1){//支部管理员
			admin.setAdminLevel(SessionConstants.ADMIN_FIRST_LEVEL);//1
			admin.setAdminManageBranchId(secondPa);
		}else{//分党委管理员 
			admin.setAdminLevel(SessionConstants.ADMIN_SECOND_LEVEL);//2
			admin.setAdminManageBranchId(firstPa);
		}
		
		admin.setAdminName(adminName);
		admin.setAdminNationality(adminNationality);
		admin.setAdminNo(adminNO);
		admin.setAdminPassword(adminPassword);
		admin.setAdminTelephone(telephone);
		//删除标记
		admin.setIsDelete(0);
		
		
		adminService.saveOrUpdateAdmin(admin);
		
		result = "添加用户成功！";
		
		
		return "save_addAdministrator";
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * 成员列表
	 * @return
	 */
	public String  memberList(){
		if(!this.checkForAuth(SessionConstants.ADMIN_FIRST_LEVEL)&& !this.checkForAuth(SessionConstants.ADMIN_SECOND_LEVEL)&& !this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL )) return "noPermission";
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(this.pageNow == null ) pageNow = 1;
		
		totalResults = 0;
		
		paginationCode = "";
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		if(firstPa!= -1){
			List<Branch> list = new ArrayList<Branch>();//
			list = branchService.findChildBranchesById(firstPa);
			if(list!=null && list.size()>0) {
				//将支部类表赋值
				secondPaList = list;
			}
		}
				
		
		//获得所管理支部的id集合
		List<Branch> branchList= branchService.getBranchlevel3(branchId);
		Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
		if(branchList.size()>0){
			for(int i=0;i<branchList.size();i++){
				branch_ids.add(branchList.get(i).getId());
			}
		}
	    
	    
	    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
	    
		
	    //将查询条件传到前台，初始值为-1   “”
	    request.setAttribute("highLevelQuery", highLevelQuery);
	    request.setAttribute("queryContent", queryContent);
	    request.setAttribute("secondPa", secondPa);
	    
	    //进入查询页时执行的方法
		DetachedCriteria countCriteria = studentService.getDetachedCriteria(highLevelQuery, queryContent ,firstPa,secondPa);//
		countCriteria.add(Restrictions.in("studentBranchId", branch_ids));
		countCriteria.add(Restrictions.eq("isDelete", 0)); 
		totalResults = studentService.queryStudentCountWithCriteria(countCriteria);  //查学生总人数
		
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;//计算一下总页数
		
		//传过来的查询参数
		DetachedCriteria detachedCriteria = studentService.getDetachedCriteria(highLevelQuery, queryContent,firstPa,secondPa);
		detachedCriteria.add(Restrictions.in("studentBranchId", branch_ids));
		detachedCriteria.add(Restrictions.eq("isDelete", 0));
		detachedCriteria.addOrder(Order.asc("studentNo"));
		
		
		//wangdong当前显示的student list
		currentStudentList = studentService.queryStudentWithCriteria(detachedCriteria, pageNow, pageSize);
		//支部id转换为branchName
		Set<Integer> branchIdSet = new HashSet<Integer>();
		for(Student student:currentStudentList){
			branchIdSet.add(student.getStudentBranchId());
		}
		branchIdToNameMap  = this.getBranchNameByBranchId(branchIdSet);
		
		//上一页，下一页
		if(totalResults > 0) paginationCode = Pagination.getPaginationCodeByConditons2(pageSize, totalResults, pageNow, highLevelQuery, queryContent, firstPa, secondPa);
		
		else paginationCode = "没有查询到有效数据！";		
		
		
		
		return "memberList";
	}
	
	/**
	 * 进入修改个人密码界面UI
	 * @return
	 */
	public String  modifyAdminPassword(){
		
		return "modifyAdminPassword";
	}
	
	/**
	 * 保存修改个人密码
	 * @return
	 */
	public String  save_modifyAdminPassword(){
		 HttpSession session = request.getSession();
			
		 Admin session_admin = (Admin)session.getAttribute(SessionConstants.SESSION_USER);
		 
		 Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		 //首先检查旧的密码是不是正确
		 if((admin.getAdminPassword()).equals(oldPassword)){//旧的密码正确
			 
		 boolean bl =adminService.savePasswordByAdminNO(admin.getAdminNo(), newPassword);
		
		 if(bl==true){
		 result = "密码修改成功！";
		 }else{
		 result = "密码修改失败！";
		 }
		
		 }else{//旧的密码错误
		 result = "提示：旧密码输入错误，请返回重新修改！";
		 }
		
		 request.setAttribute("result", result);
		
		
		return "save_modifyAdminPassword";
	}
	
	
	
	
	/**
	 * 分党委学习情况统计，分页显示
	 * @return
	 */
	public String  partyStudyStatistics(){
		
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		
		//查询出需要的记录数量放置到dto
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		if(this.pageNow == null ) pageNow = 1;
			
		totalResults = 0;
		
		paginationCode = "";
		
		
		//获得所管理分党委的id集合
		List<Branch> branchList= branchService.findChildBranchesById(1);//获得分党委列表
		Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
		if(branchList.size()>0){
			for(int i=0;i<branchList.size();i++){
				branch_ids.add(branchList.get(i).getId());
			}
		}
	    
	    
	    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
			    
				
	    //将查询条件传到前台
	    request.setAttribute("year", year);
	    request.setAttribute("currentYear", currentYear);
		
		
		
		totalResults = learnRecordService.getPartyCountByCondotions(branch_ids,currentYear); //获得所有的查询的范围内的分党委的个数
	
	    //计算总页数。
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
		
		//按照year查询 一定数量的记录
		partyStudyRecordList = learnRecordService.getPartyStudyRecordDTOByConditions(branch_ids,currentYear,pageNow,pageSize);
		
		//当日志里面没有学生学习的时候，查到的日志是空的。 怎么才能初始化为0呢？sql语句优化。。。want to do
		if(partyStudyRecordList!=null){
			
			//支部id转换为rate
			Set<Integer> partyIdSet = new HashSet<Integer>();
			for(PartyStudyRecordDTO partyDTO:partyStudyRecordList){
				//这里是分党委id，需要进一步得到分党委的下级支部的
				partyIdSet.add(partyDTO.getId());
			}
			
			branchIdToRateMap  = this.getPaticpateRateByPartyId(partyIdSet,currentYear);
		}
			
			
		
		
		
		if(totalResults > 0) paginationCode = Pagination.getPaginationCodeByYear(pageSize, totalResults, pageNow, currentYear);
		
		else paginationCode = "没有查询到有效数据！";

		
		
		return "partyStudyStatistics";
	}
	
	
	/**
	 * 支部学习情况统计，分页显示
	 * @return
	 */
	public String  branchStudyStatistics(){
		
		if(this.checkForAuth(SessionConstants.ADMIN_FIRST_LEVEL)) return "noPermission";
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		if(this.pageNow == null ) pageNow = 1;
			
		totalResults = 0;
		
		paginationCode = "";
		
		//获得所管理支部的id集合
		List<Branch> branchList= branchService.getBranchlevel3(branchId);
		Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
		if(branchList.size()>0){
			for(int i=0;i<branchList.size();i++){
				branch_ids.add(branchList.get(i).getId());
			}
		}
	    
	    
	    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
			    
				
	    //将查询条件传到前台
	    request.setAttribute("year", year);
	    request.setAttribute("currentYear", currentYear);
			    
	    //进入查询页时执行的方法
	    totalResults = learnRecordService.getBranchCountByCondotions(branch_ids, currentYear); 
	
	    //计算总页数。
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
		
		//按照year查询 一定数量pagesize的记录
		branchStudyRecordList = learnRecordService.getBranchStudyRecordDTOByConditions(branch_ids,currentYear,pageNow,pageSize);
		
		//当日志里面没有学生学习的时候，查到的日志是空的。 怎么才能初始化为0呢？
		if(branchStudyRecordList!=null){
			
			//支部id转换为rate
			Set<Integer> branchIdSet = new HashSet<Integer>();
			for(BranchStudyRecordDTO branchDTO:branchStudyRecordList){
				branchIdSet.add(branchDTO.getId());
			}
			branchIdToRateMap  = this.getPaticpateRateByBranchId(branchIdSet,currentYear);
		}
		
		
		
		if(totalResults > 0) paginationCode = Pagination.getPaginationCodeByYear(pageSize, totalResults, pageNow, currentYear);
		
		else paginationCode = "没有查询到有效数据！";

		return "branchStudyStatistics";
	}
	
	/**
	 * 个人学习情况统计，分页显示
	 * @return
	 */
	public String  personStudyStatistics(){
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(this.pageNow == null ) pageNow = 1;
		
		totalResults = 0;
		
		paginationCode = "";
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		
		if(firstPa!= -1){
			List<Branch> list = new ArrayList<Branch>();//
			list = branchService.findChildBranchesById(firstPa);
			if(list!=null && list.size()>0) {
				//将支部类表赋值
				secondPaList = list;
			}
		}
				
		
		//获得所管理支部的id集合
		List<Branch> branchList= branchService.getBranchlevel3(branchId);
		Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
		if(branchList.size()>0){
			for(int i=0;i<branchList.size();i++){
				branch_ids.add(branchList.get(i).getId());
			}
		}
	    
	    
	    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
	    
		
	    //将查询条件传到前台，初始值为-1   “”
	    request.setAttribute("year", year);
	    request.setAttribute("studentNO", studentNO);
	    request.setAttribute("studentName", studentName);
	    request.setAttribute("currentYear", currentYear);
	    
	    
	    //进入查询页时执行的方法
	    totalResults = learnRecordService.getStudentCountByCondotions(branch_ids, currentYear, studentNO, studentName, firstPa, secondPa);  
		
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;//计算一下总页数
		
		//传过来的查询参数
		
		
		//wangdong
		personStudyRecordList = learnRecordService.queryPersonLearnRecordByYear(branch_ids, currentYear, studentNO, studentName, firstPa, secondPa,pageNow,pageSize);
		
		
		//上一页，下一页
		if(totalResults > 0) paginationCode = Pagination.getPaginationCodeByConditons(pageSize, totalResults, pageNow, currentYear,studentName, studentNO,  firstPa, secondPa);
				
		
		else paginationCode = "没有查询到有效数据！";	
		
		return "personStudyStatistics";
	}
	
	
	/**
	 * 重置密码UI
	 * @return
	 */
	public String  resetUserPassword(){
		
		return "resetUserPassword";
	}
	
	
	/**
	 * 重置密码保存
	 * @return
	 */
	public String  save_resetUserPassword(){
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		if(userstatus.equals("1")){//学生账号
			//判断这个学号是不是在管理的支部内
			
			Student student = new  Student();
			//首先获得level 
			int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
			if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
				
				student = studentService.findStudentByStudentNOAndBranchId(userId,branchId);
				
			}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//分党委管理员
				
				//获得所管理支部的id集合
				List<Branch> branchList= branchService.getBranchlevel3(branchId);
				Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
				if(branch_ids != null && branchList.size()>0){
					for(int i=0;i<branchList.size();i++){
						branch_ids.add(branchList.get(i).getId());
					}
				}
				
				student = studentService.findStudentByStudentNOAndBranchIds(userId,branch_ids);
				
			}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//校党委管理员
				
				student = studentService.findStudentByStudentNO(userId);
				
			}
			
			 
			if(student!=null&&student.getId()!=null){
				student.setstudentPassword(userNewPassword);
				studentService.saveOrUpdateStudent(student);
				result = "重置密码成功！";
			}else{
				result = "用户账号错误，重置密码失败！";
			}
			
		}else {//管理员账号
			//判断这个工号是不是在管理的组织内
			
			Admin admin_user = new  Admin();
			//首先获得level 
			int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
			if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
				
				admin_user = null;
				
			}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//分党委管理员
				
				//获得所管理支部的id集合
				List<Branch> branchList= branchService.getBranchlevel3(branchId);
				Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
				if(branch_ids != null && branchList.size()>0){
					for(int i=0;i<branchList.size();i++){
						branch_ids.add(branchList.get(i).getId());
					}
				}
				
				admin_user = adminService.findAdminByAdminNOAndBranchIds(userId,branch_ids);
				
			}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//校党委管理员
				
				admin_user = adminService.findAdminByAmdinNO(userId);
				
			}
			
			
			
	
			if(admin_user!=null&&admin_user.getId()!=null){
				admin_user.setAdminPassword(userNewPassword);
				adminService.saveOrUpdateAdmin(admin_user);
				result = "重置密码成功！";
			}else{
				result = "用户账号错误，重置密码失败！";
			}
			
		}
		 
		 request.setAttribute("result", result);
		
		
		return "save_resetUserPassword";
	}
	
	
	
	
	
	
	//管理员个人信息UI
	public String adminInfo(){
		if(!this.checkForAuth(SessionConstants.ADMIN_FIRST_LEVEL)&& !this.checkForAuth(SessionConstants.ADMIN_SECOND_LEVEL)&& !this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL )) return "noPermission";
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		
		String branchName = branchService.getBranchName(admin.getAdminManageBranchId());
		
		request.setAttribute("admin", admin);
		request.setAttribute("branchName", branchName);
		return "adminInfo";
	}
	
	/**
	 * 保存管理员个人信息
	 * @return
	 */
	public String save_adminInfo(){
		Admin admin = adminService.findAdminByAmdinNO(adminNO);
		admin.setAdminName(adminName);
		admin.setAdminIdentity(sfzNO);
		admin.setAdminGender(adminGender);
		admin.setAdminNationality(adminNationality);
		admin.setAdminTelephone(telephone);
		admin.setAdminEmail(email);
		
		adminService.saveOrUpdateAdmin(admin);
		
		return "save_adminInfo";
	}
	
	
	//查看学生信息
	public String viewStudentInfo(){
		//根据学号查到学生信息
		Student student  = studentService.findStudentByStudentNO(studentNO);
		if(student!=null&&student.getStudentBranchId()!=null){
			branchName = branchService.getBranchName(student.getStudentBranchId());
			request.setAttribute("branchName", branchName);
		}
		request.setAttribute("student", student);
		
		
		return "viewStudentInfo";
	}
	
	
	
	//修改学生信息的UI
	public String modifyStudentInfo(){
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		//获得管理员管理的组织id
		int  branchId = admin.getAdminManageBranchId();
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		
		//根据学号查到学生信息
		Student student  = studentService.findStudentByStudentNO(studentNO);
		if(student!=null){
			secondPa = student.getStudentBranchId();
			Branch parent_branch = branchService.getParentBranchById(secondPa);
			firstPa = parent_branch.getId();
		}
		
		if(firstPa!=-1){
			secondPaList = branchService.findChildBranchesById(firstPa);
		}
		
		request.setAttribute("student", student);
		
		
		return "modifyStudentInfo";
	}
	
	
	//保存修改学生信息
	public String save_modifyStudentInfo(){
		
		Student student  = studentService.findStudentByStudentNO(studentNO);
		
		
		student.setStudentEmail(studentEmail);
		student.setStudentGender(studentGender);
		student.setStudentIdentity(studentSfzNO);
		student.setStudentName(studentName);
		student.setStudentNationality(studentNationality);
		student.setStudentTelephone(studentTelephone);
		
		student.setStudentBranchId(secondPa);//第三级别‘支部’
		studentService.saveOrUpdateStudent(student);
		
		return "toMemberList";
	}
	
	
	
	
	
	//删除学生
	public String  deleteStudent(){
		
		boolean bl = studentService.deleteStudent(studentNO);//删除标记置为1
		if(bl==true){
			result = "删除成功！";
		}else{
			result = "删除失败！";
		}
		
		return "toMemberList";
	}
	
	
	
	
	//管理员信息维护
	public String  adminList(){
		if(this.checkForAuth(SessionConstants.ADMIN_FIRST_LEVEL )) return "noPermission";
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(this.pageNow == null ) pageNow = 1;
		
		totalResults = 0;
		
		paginationCode = "";
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		
		if(firstPa!= -1){
			List<Branch> list = new ArrayList<Branch>();//
			list = branchService.findChildBranchesById(firstPa);
			if(list!=null && list.size()>0) {
				//将支部类表赋值
				secondPaList = list;
			}

			
		}
		
	    //将查询条件传到前台，初始值为-1   “”
	    request.setAttribute("highLevelQuery", highLevelQuery);
	    request.setAttribute("queryContent", queryContent);
	    request.setAttribute("secondPa", secondPa);
	    
	    //进入查询页时执行的方法（数量条件构造）
		DetachedCriteria countCriteria = adminService.getDetachedCriteria(highLevelQuery, queryContent ,firstPa,secondPa,admin.getAdminNo());//把管理员的工号传过去。
		countCriteria.add(Restrictions.eq("isDelete", 0));
		totalResults = adminService.queryAdminCountWithCriteria(countCriteria);  //查管理员总人数
		
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;//计算一下总页数
		
		//传过来的查询参数（人数条件构造）
		DetachedCriteria detachedCriteria = adminService.getDetachedCriteria(highLevelQuery, queryContent,firstPa,secondPa,admin.getAdminNo());//把管理员的工号传过去。
		detachedCriteria.add(Restrictions.eq("isDelete", 0));
		detachedCriteria.addOrder(Order.asc("adminName"));
		
		
		//wangdong当前显示的admin list
		currentAdminList = adminService.queryAdminWithCriteria(detachedCriteria, pageNow, pageSize);
		//支部id转换为branchName
		Set<Integer> branchIdSet = new HashSet<Integer>();
		for(Admin admin_user:currentAdminList){
			branchIdSet.add(admin_user.getAdminManageBranchId());
		}
		branchIdToNameMap  = this.getBranchNameByBranchId(branchIdSet);
		
		//上一页，下一页
		if(totalResults > 0) paginationCode = Pagination.getPaginationCodeByConditons2(pageSize, totalResults, pageNow, highLevelQuery, queryContent, firstPa, secondPa);
		
		else paginationCode = "没有查询到有效数据！";		
		
		
		
		return "adminList";
	}
	
	
	//查看管理员信息
	public String viewAdminInfo(){
		
		//根据工号查到管理员的信息
		Admin admin_user  = adminService.findAdminByAmdinNO(adminNO);
		if(admin_user!=null){
			int branchID = admin_user.getAdminManageBranchId();
			branchName = branchService.getBranchName(branchID);
		}
		request.setAttribute("admin", admin_user);
		
		return "viewAdminInfo";
	}
	
	
	//修改管理员信息
	public String modifyAdminInfo(){
		
		//根据工号查到管理员的信息
		Admin admin_user  = adminService.findAdminByAmdinNO(adminNO);
		int branchID = admin_user.getAdminManageBranchId();
		branchName = branchService.getBranchName(branchID);
		request.setAttribute("admin", admin_user);
		
		return "modifyAdminInfo";
	}
	
	
	/**
	 * 修改之后保存管理员个人信息
	 * @return
	 */
	public String save_modifyAdminInfo(){
		Admin admin = adminService.findAdminByAmdinNO(adminNO);
		admin.setAdminName(adminName);
		admin.setAdminIdentity(sfzNO);
		admin.setAdminGender(adminGender);
		admin.setAdminNationality(adminNationality);
		admin.setAdminTelephone(telephone);
		admin.setAdminEmail(email);
		
		adminService.saveOrUpdateAdmin(admin);
		
		return "toAdminList";
	}
	
	//删除管理员
	public String deleteAdmin(){
		
		boolean bl = adminService.deleteAdminByAdminNO(adminNO);//删除标记置为1
		if(bl==true){
			result = "删除成功！";
		}else{
			result = "删除失败！";
		}
		
		
		return "toAdminList";
	}
	
	
	
	//axis 根据parentId获得孩子列表
	public String getChildrenPaByParentId() {
		
		List<Branch> list = new ArrayList<Branch>();//
		
		HttpSession session = request.getSession();
		Admin session_admin  = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());//工号是不会变的。
		
		
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//如果是支部管理员
			Branch branch = branchService.findBranchById(admin.getAdminManageBranchId());
			list.add(branch);
		}else{//分党委管理员
			list = branchService.findChildBranchesById(parentId);
		}
		
		
		StringBuffer sb = new StringBuffer("<buptbranches>");
		response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");
		
		if(list!=null && list.size()>0){
			for(Iterator<Branch> it = list.iterator(); it.hasNext(); ) {
				Branch branch = it.next();
				sb.append("<id>");
				sb.append(branch.getId());
				sb.append("</id>");
				sb.append("<branchName>");
				sb.append(branch.getBranchName());
				sb.append("</branchName>");
			}
		}else{
			sb.append("<id>");
			sb.append("");
			sb.append("</id>");
		}
		
		
		sb.append("</buptbranches>");
		xmlString = sb.toString();
		
		try {
			response.getWriter().write(xmlString);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	} 
	
	
	
	
	
	public Map<Integer,String> getBranchNameByBranchId(Set<Integer> branchIdSet){
		
		if( branchIdSet == null || branchIdSet.size() <= 0) return null;
		
		Map<Integer,String> result = new HashMap<Integer,String>();
		
		for(Integer brachId:branchIdSet){
			
			String branchName = this.branchService.getBranchName(brachId);
			
			if(branchName == null) branchName="";
				
			result.put(brachId, branchName);
		}
		
		return result;
	}
	
	
	
	//计算参与率。给你一个党支部id，计算他的参与率。
	public Map<Integer,String>  getPaticpateRateByBranchId(Set<Integer> branchIdSet,String year){
		
		if( branchIdSet == null || branchIdSet.size() <= 0) return null;
		
		Map<Integer,String> result = new HashMap<Integer,String>();
		
		
		
		for(Integer branchId:branchIdSet){
			
			//支部总人数（有效人数）
			int studentCount = studentService.getStudentCountByBranchId(branchId);
			
			//支部学生‘学习时长数组’
			double[] studentStudyTimeArray  = new double[studentCount];
			int j = 0;
			String rate = "";
			List studentStudyTimeList = learnRecordService.getStudentStudyTimeByBranchId(branchId,year);
			
			if(studentStudyTimeList==null || studentStudyTimeList.size() == 0) 
				rate="0.0";
			else{
				for(Iterator<Double> it = studentStudyTimeList.iterator();it.hasNext();){
					studentStudyTimeArray[j++] = it.next();
				}
			}
			
			
			double particpateRate = BuptPartyConfig.calculateParticipateRate(studentStudyTimeArray, studentCount);
					
			rate = particpateRate+"";
				
			result.put(branchId, rate);
		}
		
		return result;
		
	}
	
	
	
	
	//计算参与率。给你一个分党委id，计算他的参与率。
		public Map<Integer,String>  getPaticpateRateByPartyId(Set<Integer> partyIdSet,String year){
			
			if( partyIdSet == null || partyIdSet.size() <= 0) return null;
			
			Map<Integer,String> result = new HashMap<Integer,String>();
			
			
			
			for(Integer branchId:partyIdSet){
				
				//分党委总人数（有效人数）
				int studentCount = studentService.getStudentCountByBranchId(branchId);
				
				//分党委学生‘学习时长数组’
				double[] studentStudyTimeArray  = new double[studentCount];
				int j = 0;
				String rate = "";
				
				//获得该分党委的下属支部的id集合
				List<Branch> branchList= branchService.findChildBranchesById(branchId);
				Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
				if(branchList!=null && branchList.size()>0){
					for(int i=0;i<branchList.size();i++){
						branch_ids.add(branchList.get(i).getId());
					}
				}
				
				List studentStudyTimeList = learnRecordService.getStudentStudyTimeByPartyId(branch_ids,year);
				
				if(studentStudyTimeList==null || studentStudyTimeList.size() == 0) 
					rate="0.0";
				else{
					for(Iterator<Double> it = studentStudyTimeList.iterator();it.hasNext();){
						studentStudyTimeArray[j++] = it.next();
					}
				}
				
				
				
				double particpateRate = BuptPartyConfig.calculateParticipateRate(studentStudyTimeArray, studentCount);
						
				rate = particpateRate+"";
					
				result.put(branchId, rate);
			}
			
			return result;
			
		}
	
		//检查管理员权限
		public boolean checkForAuth(int requiredLevel){
			
			HttpSession session = request.getSession();
			
			Object user = session.getAttribute(SessionConstants.SESSION_USER); 
			
			if(!(user instanceof Admin)) return false;
			
			Admin admin	 = (Admin) user;
			
			return admin.getAdminLevel() == requiredLevel;
		}
		
	    
	    
		//导出查询出的学生列表信息。
		public String exportStudentInfo() throws Exception{
			
			HttpSession session = request.getSession();
			Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
			
			Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
			int branchId = admin.getAdminManageBranchId();
			
			
			//获得所管理支部的id集合
			List<Branch> branchList= branchService.getBranchlevel3(branchId);
			Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
			if(branchList.size()>0){
				for(int i=0;i<branchList.size();i++){
					branch_ids.add(branchList.get(i).getId());
				}
			}
		    
			//生成secondPaList
			if(firstPa!= -1){
				List<Branch> list = new ArrayList<Branch>();//
				list = branchService.findChildBranchesById(firstPa);
				//将支部类表赋值
				secondPaList = list;
			}
			
		    
		    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
		    
		    
			//传过来的查询参数
			DetachedCriteria detachedCriteria = studentService.getDetachedCriteria(highLevelQuery, queryContent,firstPa,secondPa);
			detachedCriteria.add(Restrictions.in("studentBranchId", branch_ids));
			detachedCriteria.add(Restrictions.eq("isDelete", 0));
			detachedCriteria.addOrder(Order.asc("studentNo"));
			
			List<Student> studentList = studentService.queryStudentWithCriteria(detachedCriteria, pageNow, 0);//pageSize=0时候， 查询所有的记录。
			
			
			
			
			if(studentList != null && studentList.size() > 0 ){
				//支部id转换为branchName
				Set<Integer> branchIdSet = new HashSet<Integer>();
				for(Student student:studentList){
					branchIdSet.add(student.getStudentBranchId());
				}
				branchIdToNameMap  = this.getBranchNameByBranchId(branchIdSet);
			}
			//产生文件名
			String filename = this.createFilename("StudentInfo.xls");
			String filepath = this.createFilepath(filename);
		
			FileOutputStream os = new FileOutputStream(filepath);
			WritableWorkbook wb = Workbook.createWorkbook(os);
			WritableSheet sheet = wb.createSheet("Student", 0);
			//产生第一行标题
				sheet.addCell(new Label(0,0,"姓名"));
				sheet.addCell(new Label(1,0,"学号"));
				sheet.addCell(new Label(2,0,"身份证号"));
				sheet.addCell(new Label(3,0,"性别"));
				sheet.addCell(new Label(4,0,"民族"));
				sheet.addCell(new Label(5,0,"所属组织"));
				sheet.addCell(new Label(6,0,"联系电话"));
				sheet.addCell(new Label(7,0,"电子邮箱"));
				
				if(studentList!=null){//当查询的数据不为空的时候。
					for(int i=0;i<studentList.size();i++)
					{
						Student u =  studentList.get(i);
						//将数据写入到excel中
						sheet.addCell(new Label(0,i+1,(String) u.getStudentName()));
						sheet.addCell(new Label(1,i+1,(String) u.getStudentNo()));
						sheet.addCell(new Label(2,i+1,(String) u.getStudentIdentity()));
						if(u.getStudentGender() != null) {
							if((u.getStudentGender()).equals("1")) sheet.addCell(new Label(3,i+1,"男"));
							else sheet.addCell(new Label(3,i+1,"女"));
						}
						if(u.getStudentNationality() != null)sheet.addCell(new Label(4,i+1,Nationality.getNationality(u.getStudentNationality())));
						if(u.getStudentBranchId() != null) sheet.addCell(new Label(5,i+1,branchIdToNameMap.get(u.getStudentBranchId())));
						if(u.getStudentTelephone() != null) sheet.addCell(new Label(6,i+1,u.getStudentTelephone()));
						if(u.getStudentEmail() != null) sheet.addCell(new Label(7, i+1,u.getStudentEmail()));
					}
				}
				
				try
				{
					wb.write();
					wb.close();
					this.downloads = "excel"+ File.separator + filename;
					this.fileFileName = filename;
					request.setAttribute("filename", filename);
					return "success";
				}
				catch(Exception e)
				{
					e.printStackTrace();
					return "error";
				}
			
		}
		
		
		//导出查询的管理员的信息。
		public String exportAdminInfo(){
			
			HttpSession session = request.getSession();
			Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
			
			Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
			int branchId = admin.getAdminManageBranchId();
			
			
			//获得所管理支部的id集合
			List<Branch> branchList= branchService.getBranchlevel3(branchId);
			Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
			if(branchList.size()>0){
				for(int i=0;i<branchList.size();i++){
					branch_ids.add(branchList.get(i).getId());
				}
			}
		    
		    
		    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
		    
		    
			//传过来的查询参数
		    DetachedCriteria detachedCriteria = adminService.getDetachedCriteria(highLevelQuery, queryContent,firstPa,secondPa,admin.getAdminNo());//把管理员的工号传过去。
			detachedCriteria.add(Restrictions.eq("isDelete", 0));
			detachedCriteria.addOrder(Order.asc("adminName"));
			
			
			
			List<Admin>  adminList = adminService.queryAdminWithCriteria(detachedCriteria, pageNow, 0);
			if(adminList!=null)  {
				//支部id转换为branchName
				Set<Integer> branchIdSet = new HashSet<Integer>();
				for(Admin admin_user:adminList){
					branchIdSet.add(admin_user.getAdminManageBranchId());
				}
				branchIdToNameMap  = this.getBranchNameByBranchId(branchIdSet);
			}
			
			
			
			//产生文件名
			String filename = this.createFilename("AdminInfo.xls");
			String filepath = this.createFilepath(filename);
			try
			{
			FileOutputStream os = new FileOutputStream(filepath);
			WritableWorkbook wb = Workbook.createWorkbook(os);
			WritableSheet sheet = wb.createSheet("Administrator", 0);
			//产生第一行标题
				sheet.addCell(new Label(0,0,"姓名"));
				sheet.addCell(new Label(1,0,"工号"));
				sheet.addCell(new Label(2,0,"身份证号"));
				sheet.addCell(new Label(3,0,"性别"));
				sheet.addCell(new Label(4,0,"民族"));
				sheet.addCell(new Label(5,0,"管理组织"));
				sheet.addCell(new Label(6,0,"联系电话"));
				sheet.addCell(new Label(7,0,"电子邮箱"));
				
				if(adminList!=null){//查询出数据不为空。
					for(int i=0;i<adminList.size();i++)
					{
						Admin u =  adminList.get(i);
						//将数据写入到excel中
						sheet.addCell(new Label(0,i+1,(String) u.getAdminName()));
						sheet.addCell(new Label(1,i+1,(String) u.getAdminNo()));
						sheet.addCell(new Label(2,i+1,(String) u.getAdminIdentity()));
						if(u.getAdminGender() != null) {
							if((u.getAdminGender()).equals("1")) sheet.addCell(new Label(3,i+1,"男"));
							else sheet.addCell(new Label(3,i+1,"女"));
						}
						if(u.getAdminNationality() != null)sheet.addCell(new Label(4,i+1,Nationality.getNationality(u.getAdminNationality())));
						if(u.getAdminManageBranchId() != null) sheet.addCell(new Label(5,i+1,branchIdToNameMap.get(u.getAdminManageBranchId())));
						if(u.getAdminTelephone() != null) sheet.addCell(new Label(6,i+1,u.getAdminTelephone()));
						if(u.getAdminEmail() != null) sheet.addCell(new Label(7, i+1,u.getAdminEmail()));
					}
				}
				
				
					wb.write();
					wb.close();
					this.downloads = "excel"+ File.separator + filename;
					this.fileFileName = filename;
					request.setAttribute("filename", filename);
					return "success";
				}
				catch(Exception e)
				{
					e.printStackTrace();
					return "error";
				}
			
		}
		
		
		
		//导出查询的学生学习情况统计信息。
		public String exportStudentStudyStatisticsInfo(){
			
			HttpSession session = request.getSession();
			Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
			
			Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
			int branchId = admin.getAdminManageBranchId();
			
			
			//获得所管理支部的id集合
			List<Branch> branchList= branchService.getBranchlevel3(branchId);
			Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
			if(branchList.size()>0){
				for(int i=0;i<branchList.size();i++){
					branch_ids.add(branchList.get(i).getId());
				}
			}
		    
		    
		    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
		    
		  
			List<PersonStudyRecordDTO> studentStudyRecordList = learnRecordService.queryPersonLearnRecordByYear(branch_ids, currentYear, studentNO, studentName, firstPa, secondPa,pageNow,0);
			
			//产生文件名
			String filename = this.createFilename("StudentStudyStatisticsInfo.xls");
			String filepath = this.createFilepath(filename);
			
			try
			{
				FileOutputStream os = new FileOutputStream(filepath);
				WritableWorkbook wb = Workbook.createWorkbook(os);
				WritableSheet sheet = wb.createSheet("StudentStudyStatistics", 0);
				//产生第一行标题
				sheet.addCell(new Label(0,0,"年份"));
				sheet.addCell(new Label(1,0,"学号"));
				sheet.addCell(new Label(2,0,"姓名"));
				sheet.addCell(new Label(3,0,"所属组织"));
				sheet.addCell(new Label(4,0,"学习时长"));
				
				if(studentStudyRecordList!=null){//数据不为空。
					for(int i=0;i<studentStudyRecordList.size();i++)
					{
						PersonStudyRecordDTO u =  studentStudyRecordList.get(i);
						//将数据写入到excel中
						sheet.addCell(new Label(0,i+1,(String) u.getYear()));
						sheet.addCell(new Label(1,i+1,(String) u.getStudentNo()));
						sheet.addCell(new Label(2,i+1,(String) u.getStudentName()));
						sheet.addCell(new Label(3,i+1,(String) u.getBranchName()));
						sheet.addCell(new Label(4,i+1, u.getStudyTime().toString()));
					}
				}
				
				
					wb.write();
					wb.close();
					this.downloads = "excel"+ File.separator + filename;
					this.fileFileName = filename;
					request.setAttribute("filename", filename);
					return "success";
			}
			catch(Exception e)
			{
				e.printStackTrace();
				return "error";
			}
			
			
		}
			
		
		
		
		//导出查询的党支部学习情况统计信息。
		public String exportBranchStudyStatisticsInfo(){
			
			HttpSession session = request.getSession();
			Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
			
			Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
			int branchId = admin.getAdminManageBranchId();
			
			//获得所管理支部的id集合
			List<Branch> branchList= branchService.getBranchlevel3(branchId);
			Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
			if(branchList.size()>0){
				for(int i=0;i<branchList.size();i++){
					branch_ids.add(branchList.get(i).getId());
				}
			}
		    
		    
		    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
		    
		  
			List<BranchStudyRecordDTO> branchStudyRecord_List = learnRecordService.getBranchStudyRecordDTOByConditions(branch_ids, currentYear, pageNow, 0);
			
			
			if(branchStudyRecord_List!=null){
				//支部id转换为rate
				Set<Integer> branchIdSet = new HashSet<Integer>();
				for(BranchStudyRecordDTO branchDTO:branchStudyRecord_List){
					branchIdSet.add(branchDTO.getId());
				}
				branchIdToRateMap  = this.getPaticpateRateByBranchId(branchIdSet,currentYear);
			}
			
			//产生文件名
			String filename = this.createFilename("BranchStudyStatisticsInfo.xls");
			String filepath = this.createFilepath(filename);
			try
			{
				FileOutputStream os = new FileOutputStream(filepath);
				WritableWorkbook wb = Workbook.createWorkbook(os);
				WritableSheet sheet = wb.createSheet("BranchStudyStatistics", 0);
				//产生第一行标题
				sheet.addCell(new Label(0,0,"年份"));
				sheet.addCell(new Label(1,0,"党支部名称"));
				sheet.addCell(new Label(2,0,"党员总数"));
				sheet.addCell(new Label(3,0,"完成学时总数"));
				sheet.addCell(new Label(4,0,"人均完成学时数"));
				sheet.addCell(new Label(5,0,"参与率"));
				
				if(branchStudyRecord_List!=null){//数据不为空。
					for(int i=0;i<branchStudyRecord_List.size();i++)
					{
						BranchStudyRecordDTO u =  branchStudyRecord_List.get(i);
						//将数据写入到excel中
						sheet.addCell(new Label(0,i+1,(String) u.getYear()));
						sheet.addCell(new Label(1,i+1,(String) u.getName()));
						sheet.addCell(new Label(2,i+1, u.getStudentCount().toString()));
						sheet.addCell(new Label(3,i+1, u.getStutyTimeSum().toString()));
						sheet.addCell(new Label(4,i+1, u.getAverageTime().toString()));
						sheet.addCell(new Label(5,i+1, branchIdToRateMap.get(u.getId())));
					}
				}
				
				
					wb.write();
					wb.close();
					this.downloads = "excel"+ File.separator + filename;
					this.fileFileName = filename;
					request.setAttribute("filename", filename);
					return "success";
			}
			catch(Exception e)
			{
				e.printStackTrace();
				return "error";
			}
		}
			

		
		
		//导出查询的分党委学习情况统计信息。
		public String exportPartyStudyStatisticsInfo(){
			
			HttpSession session = request.getSession();
			Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
			
			Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
			int branchId = admin.getAdminManageBranchId();
			
			//获得所管理支部的id集合
			List<Branch> branchList= branchService.getBranchlevel3(branchId);
			Set<Integer> branch_ids = new HashSet<Integer>();//支部的集合
			if(branchList.size()>0){
				for(int i=0;i<branchList.size();i++){
					branch_ids.add(branchList.get(i).getId());
				}
			}
		    
		    
		    if(branch_ids == null || branch_ids.size() == 0) return "noPermission";
		    
		    
		  
			List<PartyStudyRecordDTO> partyStudyRecord_List = learnRecordService.getPartyStudyRecordDTOByConditions(branch_ids,currentYear,pageNow,0);
			
			if(partyStudyRecord_List!=null){
				//支部id转换为rate
				Set<Integer> branchIdSet = new HashSet<Integer>();
				for(PartyStudyRecordDTO branchDTO:partyStudyRecord_List){
					branchIdSet.add(branchDTO.getId());
				}
				branchIdToRateMap  = this.getPaticpateRateByPartyId(branchIdSet,currentYear);
			}
			
			//产生文件名
			String filename = this.createFilename("PartyStudyStatisticsInfo.xls");
			String filepath = this.createFilepath(filename);
			try
			{
				FileOutputStream os = new FileOutputStream(filepath);
				WritableWorkbook wb = Workbook.createWorkbook(os);
				WritableSheet sheet = wb.createSheet("PartyStudyStatistics", 0);
				//产生第一行标题
				sheet.addCell(new Label(0,0,"年份"));
				sheet.addCell(new Label(1,0,"分党委名称"));
				sheet.addCell(new Label(2,0,"党员总数"));
				sheet.addCell(new Label(3,0,"完成学时总数"));
				sheet.addCell(new Label(4,0,"人均完成学时数"));
				sheet.addCell(new Label(5,0,"参与率"));
				
				if(partyStudyRecord_List!=null){//数据不为空。
					for(int i=0;i<partyStudyRecord_List.size();i++)
					{
						PartyStudyRecordDTO u =  partyStudyRecord_List.get(i);
						//将数据写入到excel中
						sheet.addCell(new Label(0,i+1,(String) u.getYear()));
						sheet.addCell(new Label(1,i+1,(String) u.getName()));
						sheet.addCell(new Label(2,i+1, u.getStudentCount().toString()));
						sheet.addCell(new Label(3,i+1, u.getStutyTimeSum().toString()));
						sheet.addCell(new Label(4,i+1, u.getAverageTime().toString()));
						sheet.addCell(new Label(5,i+1, branchIdToRateMap.get(u.getId())));
					}
				}
				
				
					wb.write();
					wb.close();
					this.downloads = "excel"+ File.separator + filename;
					this.fileFileName = filename;
					request.setAttribute("filename", filename);
					return "success";
			}
			catch(Exception e)
			{
				e.printStackTrace();
				return "error";
			}
		}
		
		
		/*
		 * 生成excel文件的名字，格式为年_月_日_时_分_秒_StudentInfo.xls
		 */
		public  String createFilename(String  fileName)
		{
			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH) + 1;
			int day = calendar.get(Calendar.DATE);
			int hour = calendar.get(Calendar.HOUR);
			int minute = calendar.get(Calendar.MINUTE);
			int second = calendar.get(Calendar.SECOND);
			
			String filename = year + "_" + month + "_"+ day + "_" + hour + "_" + minute + "_" + second + "_"+fileName;
			return filename;
		}
		
		
		
		/*
		 * 生成文件的路径信息
		 */
		public String createFilepath(String filename)
		{
			String realpath = request.getSession().getServletContext().getRealPath("excel");
			String path = realpath + File.separator + filename;
			
			return path;
		}
		
		
		//从下载文件原始存放路径读取得到文件输出流
		public InputStream getDownloadFile() throws Exception{
			
			InputStream is = ServletActionContext.getServletContext().getResourceAsStream(
					File.separator+"excel"+File.separator + this.downloadFilename);
			return is;
		}
		
		
		//如果下载文件名字有中文，进行字符编码转换
		public String getDownloadChineseFileName() throws UnsupportedEncodingException {
			String downloadChineseFileName = new String(this.downloadFilename.getBytes(), "utf-8");
			return downloadChineseFileName;
		}
		
		
		
		public String download(){
			return "success";
		}
		
		public String playVideo(){
			if(!this.checkForAuth(SessionConstants.STU_LEVEL) ) return "loginUI";
			HttpServletRequest request = ServletActionContext.getRequest(); 
			String videopath = request.getParameter("videopath");
			String categoryId = request.getParameter("categoryId");
		
			Video target = null;
			List<Video> videoList = VideoMgr.getInstance().getVideos(categoryId, Video.STATUS_PUBLISHED);
			for(int i = 0; i < videoList.size(); i++){
				Video temp = videoList.get(i);
				if(temp.getVideopath().trim().equals(videopath.trim())){
					target = temp;
				}
			}
			request.setAttribute("videoFullPath", target.getVideopath());
			request.setAttribute("videoName", target.getName());
			return "playVideo";
		}
}

